class Solution {
    public int shipWithinDays(int[] weights, int days) {
        int left = 0;
        int right = 0;
        for (int i = 0; i < weights.length; i++) {
            left = Math.max(left, weights[i]);
            right += weights[i];
        }
        while (left < right) {
            int mid = (left + right) >> 1;
            if (canTransfer(weights, days, mid)) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return right;
    }
    private boolean canTransfer(int[] weights, int days, int capacity) {
        int weightSum = 0;
        int dayNeeded = 1;
        for (int i = 0; i < weights.length; i++) {
            int newSum = weightSum + weights[i];
            if (newSum > capacity) {
                dayNeeded++;
                weightSum = weights[i];
            } else {
                weightSum = newSum;
            }
        }
        return dayNeeded <= days;
    }
}
